import 'dart:io';

import 'package:base_lib/repository/http.dart';
import 'package:doctor_login_lib/component.dart';
import 'package:flutter/cupertino.dart';
import 'package:doctor_login_lib/cache/userinfo_cache.dart';
import 'package:doctor_login_lib/repository/http.dart';
import 'package:rxdart/rxdart.dart';
import 'package:base_lib/index.dart';
import 'package:base_lib/repository/entity/upload_file_entity.dart'
    as UploadBean;
import 'package:doctor_login_lib/login/entity/doctor_login_entity.dart'
    as DoctorLoginBean;
import 'package:base_lib/dictionary/entity/doctor_title_entity.dart'
    as TitleBean;
import 'package:base_lib/dictionary/entity/doctor_practice_entity.dart'
    as PracticeBean;
import 'package:base_lib/dictionary/entity/medical_section_entity.dart'
    as SectionBean;
import '../disease/entity/disease_entity.dart' as DiseaseBean;
import 'package:base_lib/dictionary/dictionary_provider.dart';

class SetUserInfoBloc extends BaseBloc {
  PublishSubject<bool> loadingStatus = PublishSubject();

  PublishSubject<String> header = PublishSubject();

  PublishSubject<String> name = PublishSubject();

  PublishSubject<String> hospital = PublishSubject();

  ///执照
  PublishSubject<String> doctorPractice = PublishSubject();

  ///职称
  PublishSubject<String> doctorTitle = PublishSubject();

  ///科室
  PublishSubject<String> section = PublishSubject();

  ///专治疾病
  PublishSubject<String> disease = PublishSubject();

  ///擅长
  PublishSubject<String> goodAt = PublishSubject();

  ///简介
  PublishSubject<String> briefDesc = PublishSubject();

  SectionBean.Data _sectionData;

  DoctorLoginBean.DoctorUser _doctorUser;

  @override
  void initState() async {
    super.initState();
    var doctorInfo = await UserInfoCache.getInstance().get();
    _doctorUser = doctorInfo;
    name.add(_doctorUser.doctorName);
    hospital.add(_doctorUser.doctorInfo.workPlace);
    doctorPractice.add(_doctorUser.doctorInfo.practiceName);
    section.add(_doctorUser.doctorInfo.sectionName);
    doctorTitle.add(_doctorUser.doctorInfo.titleName);
    goodAt.add(_doctorUser.doctorInfo.goodAt);
    briefDesc.add(_doctorUser.doctorInfo.briefDesc);
    await getDisease(_doctorUser.keyID);
    header.add(_doctorUser.doctorInfo.photoUrl ?? '');
  }

  @override
  void dispose() {
    header?.close();
    name?.close();
    hospital?.close();
    loadingStatus?.close();
    doctorPractice?.close();
    doctorTitle?.close();
    section?.close();
    disease?.close();
    goodAt?.close();
    briefDesc?.close();
  }

  ///更新用户信息
  void updateUserInfo(BuildContext context) async {
    if (_doctorUser.doctorInfo.photoUrl.isEmpty ?? true) {
      ToastUtil.warning("请上传工作照");
      return;
    }

    if (_doctorUser.doctorName?.isEmpty ?? true) {
      ToastUtil.warning("请输入姓名");
      return;
    }

    if (_doctorUser.doctorInfo.workPlace?.isEmpty ?? true) {
      ToastUtil.warning("请输入医院（诊所）");
      return;
    }

    if (_doctorUser.doctorInfo.practiceCode?.isEmpty ?? true) {
      ToastUtil.warning("请选择执业类型");
      return;
    }

    if (_doctorUser.doctorInfo.sectionCode?.isEmpty ?? true) {
      ToastUtil.warning("请选择科室");
      return;
    }

    if (_doctorUser.doctorInfo.titleCode?.isEmpty ?? true) {
      ToastUtil.warning("请选择职称");
      return;
    }

    loadingStatus.add(true);
    await UserInfoCache.getInstance().cacheData(_doctorUser);
    var result = await LoginHttp.saveDoctorInfo(_doctorUser);
    loadingStatus.add(false);
    if (result.isSuccess) {
      Routers.navigateTo(context, DoctorLoginComponent.certificationPage);
    } else {
      ToastUtil.show(result?.error?.msg ?? "");
    }
  }

  void editNameChanged(String value) {
    _doctorUser.doctorName = value;
  }

  void editHospitalChanged(String value) {
    _doctorUser.doctorInfo.workPlace = value;
  }

  ///获取执照
  Future<List<PracticeBean.Data>> getPractice() async {
    var result = await DictionaryProvider.getPractice();
    if (result.isSuccess) {
      var data = PracticeBean.DoctorPracticeEntity.fromJson(result.data);
      return data.data;
    } else {
      ToastUtil.show(result.error.msg);
      return [];
    }
  }

  setDoctorPractice(PracticeBean.Data value) {
    _doctorUser.doctorInfo
      ..practiceName = value.dictName
      ..practiceCode = value.dictCode;
    doctorPractice.add(value.dictName);
  }

  ///获取职称
  Future<List<TitleBean.Data>> getTitles() async {
    var result = await DictionaryProvider.getTitles();
    if (result.isSuccess) {
      var data = TitleBean.DoctorTitleEntity.fromJson(result.data);
      return data.data;
    } else {
      ToastUtil.show(result.error.msg);
      return [];
    }
  }

  setDoctorTitle(TitleBean.Data value) {
    _doctorUser.doctorInfo
      ..titleName = value.dictName
      ..titleCode = value.dictCode;
    doctorTitle.add(value.dictName);
  }

  ///获取专治疾病
  getDisease(keyID) async {
    var result = await LoginHttp.getDoctorDisease(keyID);
    if (result.isSuccess) {
      var data = DiseaseBean.DoctorDiseaseEntity.fromJson(result.data);
      setDisease2page(data.data);
    } else {
      ToastUtil.show(result.error.msg);
    }
  }

  ///选择科室
  void chooseSection(BuildContext context) {
    Routers.navigateTo(context, DoctorLoginComponent.selectSectionPage,
            parameters: Parameters()
              ..putString("sectionCode", _doctorUser.doctorInfo.sectionCode))
        .then((value) {
      if (value != null) {
        _sectionData = value;
        section.add(_sectionData.dictName);
        _doctorUser.doctorInfo
          ..sectionCode = _sectionData.dictCode
          ..sectionName = _sectionData.systemName;
      }
    });
  }

  ///专治疾病
  void jump2Disease(BuildContext context) {
    Routers.navigateTo(context, DoctorLoginComponent.diseasePage,
            parameters: Parameters()..putString("keyID", _doctorUser.keyID))
        .then((value) {
      if (value is List<DiseaseBean.Data>) {
        setDisease2page(value);
      }
    });
  }

  void setDisease2page(List<DiseaseBean.Data> value) {
    var str = value.map((e) => e.diseaseName).toList().join(" , ");
    disease.add(str);
  }

  ///擅长
  void jump2GoodAt(BuildContext context) {
    Routers.navigateTo(context, DoctorLoginComponent.goodAtPage,
            parameters: Parameters()
              ..putString("goodAt", _doctorUser.doctorInfo.goodAt))
        .then((value) {
      if (value != null) {
        _doctorUser.doctorInfo.goodAt = value;
        goodAt.add(_doctorUser.doctorInfo.goodAt);
      }
    });
  }

  ///简介
  void jump2BriefDesc(BuildContext context) {
    Routers.navigateTo(context, DoctorLoginComponent.briefDescPage,
            parameters: Parameters()
              ..putString("desc", _doctorUser.doctorInfo.briefDesc))
        .then((value) {
      if (value != null) {
        _doctorUser.doctorInfo.briefDesc = value;
        briefDesc.add(_doctorUser.doctorInfo.briefDesc);
      }
    });
  }

  void saveDoctorPhoto(BuildContext context, String path) async {
    header.add('-');
    var result = await FileHttp.upload(Map()..["file"] = File(path),
        params: Map()
          ..['belongID'] = _doctorUser.keyID
          ..['systemCode'] = 'DOCTOR'
          ..['belongCode'] = 'CERTIFY'
          ..['width'] = '500'
          ..['height'] = '500');

    if (result.isSuccess) {
      doSaveDoctorPhoto(context, result.data.remoteAddress, result.data.keyID);
    } else {
      ToastUtil.error('上传失败');
      header.add('');
    }
  }

  ///上传头像
  void doSaveDoctorPhoto(
      BuildContext context, String path, String photoFileID) async {
    // let photoData = {
    //   doctorID: this.userInfo.keyID,
    //   photoUrl: "",
    //   photoFileID: data.keyID
    // };
    var result =
        await LoginHttp.saveDoctorPhoto(_doctorUser.keyID, path, photoFileID);
    if (result.isSuccess) {
      _doctorUser.doctorInfo
        ..photoFileID = photoFileID
        ..photoUrl = path;
      header.add(path);
    } else {
      header.add('');
      ToastUtil.error(result.error.msg);
    }
  }

  void deleteDoctorPhoto(BuildContext context) async {
    // let photoData = {
    //   doctorID: this.userInfo.keyID,
    //   photoUrl: "",
    //   photoFileID: data.keyID
    // };
    await LoginHttp.saveDoctorPhoto(
        _doctorUser.keyID, '', _doctorUser.doctorInfo?.photoFileID ?? '');
    header.add('');
  }
}
